package com.music.mysongs.db

import android.content.ContentResolver
import android.content.ContentUris
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import androidx.core.net.toUri
import com.music.mysongs.bean.SongBean
import com.music.mysongs.utils.myLog

@RequiresApi(Build.VERSION_CODES.Q)
//扫描音乐文件
fun musicScanLocal(
    contentResolver: ContentResolver//, list: ArrayList<MusicBean>
): Boolean {
    try {
        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            null
        )
        if (cursor != null) {
            val localMusicDBManager = MusicDataBaseManager()
            //val localBeanManager = BeanManager()
            while (cursor.moveToNext()) {
                val isMusic =
                    cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC))
                val duration =
                    cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
                //是音乐且时长大于2分钟
                if (isMusic != 0 && duration >= 2 * 60 * 1000) {
                    val path =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                            .toUri()
                    //val path = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cursor.position.toLong())
                    if (localMusicDBManager.queryExistDB(path)) {
                        continue
                    }
                    var title =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE))
                    var artist =
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST))
                    if (title.contains("-")) {
                        val str: List<String> = title.split("-")
                        title = str[0]
                        artist = str[1]
                    }
                    val bean = SongBean(
                        title,
                        artist,
                        path,
                        duration,
                        0
                    )
                    localMusicDBManager.insertDB(bean)
                }
            }
        }
        cursor?.close()
    } catch (e: Exception) {
        e.printStackTrace()
        return false
    }
    return true
}
